package com.hundsun.cprs.yyt.web.action.area;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.hundsun.cprs.yyt.common.enums.EnumAreaCode;
import com.hundsun.cprs.yyt.common.enums.EnumBusinessCode;
import com.hundsun.cprs.yyt.common.exception.ServiceCodeException;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsSpecs;
import com.hundsun.cprs.yyt.service.goods.domain.GoodsWithArea;
import com.hundsun.cprs.yyt.service.goods.domain.query.GoodsQuery;
import com.hundsun.cprs.yyt.service.goods.domain.query.GoodsStockLogQuery;
import com.hundsun.cprs.yyt.service.goods.dto.AttributeForm;
import com.hundsun.cprs.yyt.service.goods.dto.AttributeInfo;
import com.hundsun.cprs.yyt.service.goods.dto.GoodsAreaInfo;
import com.hundsun.cprs.yyt.service.goods.dto.GoodsInfo;
import com.hundsun.cprs.yyt.service.goods.dto.GoodsPublishInfo;
import com.hundsun.cprs.yyt.service.goods.enums.EnumGoodsStatus;
import com.hundsun.cprs.yyt.service.goods.enums.EnumHotGoodsType;
import com.hundsun.cprs.yyt.service.goods.enums.EnumStockType;
import com.hundsun.cprs.yyt.service.goods.service.AttributeService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsAreaSerivce;
import com.hundsun.cprs.yyt.service.goods.service.GoodsService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsSkuService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsStockLogService;
import com.hundsun.cprs.yyt.service.goods.service.GoodsWithAreaService;
import com.hundsun.cprs.yyt.service.plate.domain.Plate;
import com.hundsun.cprs.yyt.service.plate.domain.query.PlateQuery;
import com.hundsun.cprs.yyt.service.plate.service.PlateService;
import com.hundsun.cprs.yyt.service.quota.service.QuotaService;
import com.hundsun.cprs.yyt.service.system.enums.EnumBussinessParam;
import com.hundsun.cprs.yyt.service.system.service.BusinessParamHelper;
import com.hundsun.cprs.yyt.service.system.service.BussinessParamService;
import com.hundsun.cprs.yyt.util.BeanUtils;
import com.hundsun.cprs.yyt.util.DateUtil;
import com.hundsun.cprs.yyt.util.DoubleUtil;
import com.hundsun.cprs.yyt.web.action.BaseAction;
import com.hundsun.cprs.yyt.web.vo.JsonModel;

@Controller
public class AreaAction extends BaseAction {
    
    private static final String PATH_WHOLESALE_AREA_CODE = "wholesaleArea";
    
    private static final String PATH_RETAIL_AREA_CODE = "retailArea";

    @Autowired
    private GoodsService goodsService;
    @Autowired
    private PlateService plateService;
    @Autowired
    private GoodsWithAreaService goodsWithAreaService;
    @Autowired
    private GoodsSkuService goodsSkuService;
    @Autowired
    private AttributeService attributeService;
    @Autowired
    private GoodsStockLogService goodsStockLogService;
    @Autowired
    private BussinessParamService bussinessParamService;
    @Autowired
    private GoodsAreaSerivce goodsAreaSerivce;
    @Autowired
    private QuotaService quotaService;

    @RequestMapping("{areaCode}/list.htm")
    public String list(@ModelAttribute("query")GoodsQuery query,@PathVariable("areaCode") String areaCode,ModelMap model){
        if (PATH_RETAIL_AREA_CODE.equals(areaCode)) {
            query.setAreaCode(EnumAreaCode.RETAIL_AREA.getCode());//零售区商品列表查询
        }
        if (PATH_WHOLESALE_AREA_CODE.equals(areaCode)) {
            query.setAreaCode(EnumAreaCode.WHOLESALE_AREA.getCode());//批发区商品列表查询
        }
        //发布时间转换
        publishTimeChans(query);
        goodsService.queryAreaGoodsList(query);
        model.addAttribute("statusMap", EnumGoodsStatus.toMap());
        return new StringBuilder("/area/").append(areaCode).append("/list").toString();
    }
    
    @RequestMapping(value="area/goods/edit",method=RequestMethod.GET)
    public String editPlate(Long goodsId,String areaCode, ModelMap model) {
        // 查询专区商品
        GoodsAreaInfo goodsAreaInfo = goodsAreaSerivce.selectByAreaCodeAndGoodsId(areaCode, goodsId.intValue());
        if (goodsAreaInfo == null) {
            return error(model, "专区商品不存在");
        }
        model.put("data", goodsAreaInfo);
        model.put("returnFlag", EnumAreaCode.RETAIL_AREA.getCode().equals(areaCode)?"retailArea":"wholesaleArea");
        
        // 加载专区专场数据
        PlateQuery query = new PlateQuery();
        query.setAreaCode(areaCode);
        model.put("plateList", plateService.selectPlateList(query));
        Plate newPlate = plateService.getNewPlate();
        if (newPlate != null) {
            model.put("newPlateCode",newPlate.getPlateCode());
        }
        return "area/goods/edit";
    }
    
    @RequestMapping(value="area/goods/edit",method=RequestMethod.POST)
    @ResponseBody
    public JsonModel editPlate(@RequestBody GoodsAreaInfo goodsAreaInfo, ModelMap model) {
        try {
            goodsAreaSerivce.updateGoodsAreaInfo(goodsAreaInfo);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS, "编辑成功");
        } catch (Exception e) {
            log.error("编辑专区商品异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL, "编辑失败"); 
        }
    }
    
    @RequestMapping("area/unbindGoodsList.htm")
    public String add(@ModelAttribute("query")GoodsQuery query,ModelMap model){
        goodsService.queryUnBindGoodsList(query);
        model.addAttribute("statusMap", EnumGoodsStatus.toMap());
        model.addAttribute("areaCode",query.getAreaCode());
        model.addAttribute("quotaList", quotaService.queryAll());
        if (query.getAreaCode().equals(EnumAreaCode.RETAIL_AREA.getCode())){
            model.put("quotaRewardRate", BusinessParamHelper.getDoubleValue(bussinessParamService, EnumBussinessParam.DEFAULT_QUOTA_REWARD_RATE));
            model.put("integralRewardRate", BusinessParamHelper.getDoubleValue(bussinessParamService, EnumBussinessParam.DEFAULT_INTEGRAL_REWARD_RATE));
            return "area/retailArea/biddingGoods";
        }else{
            model.addAttribute("attributeInfoList",attributeService.selectAttributeInfo());
            return "area/wholesaleArea/unbindGoodsList";
        }
    }

    @RequestMapping(value = "area/bindGoods.json",method = RequestMethod.POST)
    @ResponseBody
    public JsonModel addFromRetailArea(@RequestBody GoodsAreaInfo goodsAreaInfo){
        try {
            GoodsInfo goods = goodsService.selectGoodsInfoById(goodsAreaInfo.getGoodsId());
            if (goods == null) {
                throw new IllegalArgumentException("商品不存在");
            }
            BeanUtils.copyNotNullProperties(goodsAreaInfo.getGoods(), goods);
            goodsAreaInfo.setAreaCode(EnumAreaCode.RETAIL_AREA.getCode());
            goodsAreaInfo.setGoods(goods);
            goodsAreaSerivce.putOnGoods(goodsAreaInfo);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"商品上架成功");
        } catch (Exception e) {
            log.error("商品上架异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }


    /*
    * 库存调整初始化
    *
    * */
    @RequestMapping(value = "area/editStock.htm",method = RequestMethod.GET)
    public String edit(@RequestParam("areaCode")String areaCode,@RequestParam("goodsId")Integer goodsId,ModelMap model){
        GoodsInfo goodsInfo = goodsService.selectGoodsInfoById(goodsId,areaCode);
        if (goodsInfo == null) {
			return error(model, "专区商品信息不存在");
		}
        model.addAttribute("goodsInfo",	goodsInfo);
        model.addAttribute("quotaList", quotaService.queryAll());
        
        if (areaCode.equals(EnumAreaCode.RETAIL_AREA.getCode())){
            model.addAttribute("sku",goodsSkuService.selectDistinctSku(areaCode, goodsId, BigDecimal.ZERO.toString()));
            return "area/retailArea/editStock";
        }else{
            model.addAttribute("attributeInfoList",buildAttributeInfos(goodsInfo));
            model.addAttribute("attributeItemList",attributeService.selectAttributeInfo());
            return "area/wholesaleArea/editStock";
        }
    }
    
    private List<AttributeInfo> buildAttributeInfos(GoodsInfo goodsInfo) {
        if (goodsInfo.getSkus() != null && !goodsInfo.getSkus().isEmpty()) {
            List<AttributeInfo> attributeInfoList = new ArrayList<>();
            for (GoodsSpecs goodsSpecs : goodsInfo.getSkus()) {
                AttributeInfo attributeInfo = new AttributeInfo();
                List<AttributeForm> attributeFormList = new ArrayList<>();
                if (goodsSpecs.getGoodsSpecs() != null) {
                    Map<String, String> attributeFormMap = JSON.parseObject(goodsSpecs.getGoodsSpecs(), Map.class);
                    for (Map.Entry<String, String> entry : attributeFormMap.entrySet()) {
                        AttributeForm attributeForm = new AttributeForm();
                        attributeForm.setAttributeName(entry.getKey());
                        attributeForm.setAttributeValue(entry.getValue());
                        attributeFormList.add(attributeForm);
                    }
                }
                attributeInfo.setAttributeFormList(attributeFormList);
                attributeInfo.setItemPrice(goodsSpecs.getGoodsPrice());
                attributeInfo.setStockNum(goodsSpecs.getGoodsStock());
                attributeInfo.setQuotaAmount(goodsSpecs.getQuotaAmount());
                attributeInfo.setSkuId(goodsSpecs.getId());
                attributeInfo.setAllocatedStock(goodsSpecs.getAllocatedStock());
                attributeInfoList.add(attributeInfo);
            }
            return attributeInfoList;
        }
        return null;
    }

    /*
     * 批发区商品规格调整
     *
     * */
    @RequestMapping(value = "area/wholesaleArea/editStock.json",method = RequestMethod.POST)
    @ResponseBody
    public JsonModel editFromWholesaleArea(@RequestBody GoodsPublishInfo request){
        try {
        	GoodsAreaInfo goodsAreaInfo = goodsAreaSerivce.selectByAreaCodeAndGoodsId(EnumAreaCode.WHOLESALE_AREA.getCode(),request.getGoodsId());
            if (goodsAreaInfo == null) {
                throw new IllegalArgumentException("专区商品不存在");
            }
            
        	goodsAreaInfo.setSkus(parseAttributeToJson(request));
        	goodsAreaInfo.getGoods().setPayQuotaId(request.getPayQuotaId());
        	goodsAreaInfo.getGoods().setAttributeList(request.getAttributeList());
            goodsAreaInfo.getGoods().setWholesaleLimit(request.getWholesaleLimit());
        	
        	validateSkuList(goodsAreaInfo.getSkus());
        	
            goodsAreaSerivce.updateBasicGoodsAreaInfo(goodsAreaInfo);
            //goodsSkuService.editWholesaleSku(goodsInfo);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"商品规格调整成功");
        } catch (Exception e) {
            log.error("商品规格调整异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }

    /*
     * 零售区库存调整
     *
     * */
    @RequestMapping(value = "area/retailArea/editStock.json",method = RequestMethod.POST)
    @ResponseBody
    public JsonModel editFromRetailArea(@RequestBody GoodsAreaInfo goodsAreaInfo){
        try {
        	goodsAreaInfo.setAreaCode(EnumAreaCode.RETAIL_AREA.getCode());
        	GoodsAreaInfo dbGoodsAreaInfo = goodsAreaSerivce.selectByAreaCodeAndGoodsId(goodsAreaInfo.getAreaCode(),goodsAreaInfo.getGoodsId());
            if (dbGoodsAreaInfo == null) {
                throw new IllegalArgumentException("专区商品不存在");
            }
            
        	goodsAreaSerivce.updateBasicGoodsAreaInfo(goodsAreaInfo);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"商品属性编辑成功");
        } catch (Exception e) {
            log.error("商品属性编辑异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }

    /**
     * 批发区商品上架
     *
     * */
    @RequestMapping(value = "area/wholesaleArea/bindGoods.json",method = RequestMethod.POST)
    @ResponseBody
    public JsonModel addFromWholesaleArea(@RequestBody GoodsPublishInfo request){
        try {
            GoodsInfo goods = goodsService.selectGoodsInfoById(request.getGoodsId());
            if (goods == null) {
                throw new IllegalArgumentException("商品不存在");
            }
            
        	GoodsAreaInfo goodsAreaInfo = new GoodsAreaInfo();
        	goodsAreaInfo.setAreaCode(EnumAreaCode.WHOLESALE_AREA.getCode());
        	goodsAreaInfo.setGoods(goods);
        	goodsAreaInfo.setSkus(parseAttributeToJson(request));
        	goodsAreaInfo.getGoods().setPayQuotaId(request.getPayQuotaId());
        	goodsAreaInfo.getGoods().setAttributeList(request.getAttributeList());
        	goodsAreaInfo.getGoods().setWholesaleLimit(request.getWholesaleLimit());
        	
        	validateSkuList(goodsAreaInfo.getSkus());
        	
        	goodsAreaSerivce.putOnGoods(goodsAreaInfo);
            //goodsSkuService.crateWholesaleSku(goodsInfo);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"商品上架成功");
        } catch (Exception e) {
            log.error("商品上架异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }
    
    protected void validateSkuList(List<GoodsSpecs> goodsSpecsList){
        if (goodsSpecsList == null || goodsSpecsList.isEmpty()){
            throw new ServiceCodeException(EnumBusinessCode.BUSINESS_1305.getErrorNo(),EnumBusinessCode.BUSINESS_1305.getErrorInfo());
        }else{
            for (GoodsSpecs goodsSpecs : goodsSpecsList){
                Validate.notNull(goodsSpecs.getGoodsStock(), "库存不能为空");
                Validate.notNull(goodsSpecs.getGoodsPrice(), "折扣价格不能为空");
                Validate.notNull(goodsSpecs.getQuotaAmount(), "所需配额不能为空");
            }
        }
    }
    
    protected List<GoodsSpecs> parseAttributeToJson(GoodsPublishInfo goodsPublishInfo){
    	List<GoodsSpecs> goodsSpecsList = null;
        if (goodsPublishInfo.getAttributeInfoList() != null && !goodsPublishInfo.getAttributeInfoList().isEmpty()){
        	goodsSpecsList = new ArrayList<GoodsSpecs>(goodsPublishInfo.getAttributeInfoList().size());
        	
            Map<String,Set<String>> attributeMap = new LinkedHashMap();//商品属性列表转json
            Map<String,String> goodsSpecsMap = new LinkedHashMap();//商品规格转json
            for (AttributeInfo attributeInfo : goodsPublishInfo.getAttributeInfoList()){
                for (AttributeForm attributeForm : attributeInfo.getAttributeFormList()) {
                    Set<String> attributeValueList = attributeMap.get(attributeForm.getAttributeName());
                    if (attributeValueList == null){
                        attributeValueList = new HashSet<>();
                        attributeValueList.add(attributeForm.getAttributeValue());
                    }else{
                        attributeValueList.add(attributeForm.getAttributeValue());
                    }
                    attributeMap.put(attributeForm.getAttributeName(),attributeValueList);
                    goodsSpecsMap.put(attributeForm.getAttributeName(),attributeForm.getAttributeValue());
                }
                //往规格集合中插入数据
                GoodsSpecs goodsSpecs = new GoodsSpecs();
                goodsSpecs.setId(attributeInfo.getSkuId());
                if (attributeInfo.getItemPrice() != null){
                    goodsSpecs.setGoodsPrice(DoubleUtil.mul(attributeInfo.getItemPrice(),100D));
                }
                goodsSpecs.setGoodsStock(attributeInfo.getStockNum());
                goodsSpecs.setQuotaAmount(attributeInfo.getQuotaAmount());
                goodsSpecs.setGoodsSpecs(JSON.toJSONString(goodsSpecsMap));
                goodsSpecsList.add(goodsSpecs);
            }
            goodsPublishInfo.setAttributeList(JSON.toJSONString(attributeMap));
        }
        return goodsSpecsList;
    }

    /**
     * 库存变更流水
     * 分专区展示
     *
     * */
    @RequestMapping("{areaCode}/stockLog/list.htm")
    public String listStockLog(@ModelAttribute("query")GoodsStockLogQuery query,@PathVariable("areaCode") String areaCode, ModelMap model){
        if (PATH_RETAIL_AREA_CODE.equals(areaCode)) {
            query.setAreaCode(EnumAreaCode.RETAIL_AREA.getCode());
        }
        if (PATH_WHOLESALE_AREA_CODE.equals(areaCode)) {
            query.setAreaCode(EnumAreaCode.WHOLESALE_AREA.getCode());
        }
        formGoodsCodeToSkuIdList(query);
        goodsStockLogService.queryStockLogPage(query);
        model.addAttribute("stockTypeMap", EnumStockType.toMap());
        return new StringBuilder("area/stockLog/").append(areaCode).append("/list").toString();
    }

    /**
     * 成为爆款或取消爆款
     *
     * */
    @RequestMapping("area/hotGoods.json")
    @ResponseBody
    public JsonModel editHotGoods(@RequestParam("areaCode")String areaCode,@RequestParam("goodsId")Integer goodsId,@RequestParam("type")String type){
        try {
            GoodsWithArea goodsWithArea = new GoodsWithArea();
            goodsWithArea.setGoodsId(goodsId);
            goodsWithArea.setAreaCode(areaCode);
            if (type.equals(EnumHotGoodsType.HOT_GOODS.getCode())){
                goodsWithArea.setTopShow(Integer.parseInt(EnumHotGoodsType.HOT_GOODS.getCode()));
            }else if (type.equals(EnumHotGoodsType.NOT_HOT_GOODS.getCode())){
                goodsWithArea.setTopShow(Integer.parseInt(EnumHotGoodsType.NOT_HOT_GOODS.getCode()));
            }
            goodsWithAreaService.update(goodsWithArea);
            return new JsonModel(JsonModel.RESULD_CODE_SUCCESS,"操作成功");
        } catch (Exception e) {
            log.error("操作异常:",e);
            return new JsonModel(JsonModel.RESULD_CODE_FAIL,e.getMessage());
        }
    }

    private void formGoodsCodeToSkuIdList(GoodsStockLogQuery query){
        if (query.getGoodsCode() != null && query.getGoodsCode().length()>0){
            //根据商品编码查到该商品下的所有skuId集合
            List<Long> skuIdArrayList = goodsSkuService.selectSkuIdListByGoodsCode(query.getGoodsCode());
            if (skuIdArrayList.size()>0){
                query.setSkuIdArrayList(skuIdArrayList);
            }else{
                //skuid置0,使查询结果集为空
                skuIdArrayList.add(0l);
                query.setSkuIdArrayList(skuIdArrayList);
            }
        }
    }

    private void publishTimeChans(GoodsQuery query){
        if (query.getPublishTimeL() != null){
            query.setPublishTimeL(DateUtil.getBeginOfDay(query.getPublishTimeL()));
        }
        if (query.getPublishTimeR() != null){
            query.setPublishTimeR(DateUtil.getEndOfDay(query.getPublishTimeR()));
        }
    }
}
